<template>
  <el-drawer
    v-model="visible"
    title="编辑订单"
    size="500px"
    @close="handleClose"
  >
    <div class="order-edit-content" v-if="order">
      <el-form
        ref="orderFormRef"
        :model="orderForm"
        :rules="rules"
        label-width="100px"
        label-position="left"
      >
        <el-form-item label="订单编号" prop="platformOrderId">
          <el-input v-model="orderForm.platformOrderId" />
        </el-form-item>
        
        <el-form-item label="平台来源" prop="platformSource">
          <el-select v-model="orderForm.platformSource" placeholder="请选择平台来源" style="width: 100%;">
            <el-option label="政采云" value="zcy" />
            <el-option label="手工录入" value="manual" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="客户名称" prop="customerName">
          <el-input v-model="orderForm.customerName" />
        </el-form-item>
        
        <el-form-item label="联系人" prop="contactPerson">
          <el-input v-model="orderForm.contactPerson" />
        </el-form-item>
        
        <el-form-item label="订单金额" prop="amount">
          <el-input-number 
            v-model="orderForm.amount" 
            :min="0" 
            :precision="2" 
            style="width: 100%;" 
          />
        </el-form-item>
        
        <el-form-item label="订单日期" prop="orderDate">
          <el-date-picker
            v-model="orderForm.orderDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择订单日期"
            style="width: 100%;"
          />
        </el-form-item>
        
        <el-form-item label="订单状态" prop="orderStatus">
          <el-select v-model="orderForm.orderStatus" placeholder="请选择订单状态" style="width: 100%;">
            <el-option label="待付款" value="pending" />
            <el-option label="已付款" value="paid" />
            <el-option label="已发货" value="shipped" />
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="发票状态" prop="invoiceStatus">
          <el-select v-model="orderForm.invoiceStatus" placeholder="请选择发票状态" style="width: 100%;">
            <el-option label="未开票" value="uninvoiced" />
            <el-option label="已开票" value="invoiced" />
            <el-option label="已发送" value="sent" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="负责销售" prop="responsibleSalesman">
          <el-input v-model="orderForm.responsibleSalesman" />
        </el-form-item>
        
        <el-form-item label="含赠品">
          <el-switch v-model="orderForm.hasGift" />
        </el-form-item>
      </el-form>
      
      <div class="form-actions" style="margin-top: 20px; text-align: right;">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="saveOrder">保存</el-button>
      </div>
    </div>
    
    <div v-else class="loading-container">
      <el-skeleton animated>
        <template #template>
          <el-skeleton-item variant="p" style="height: 20px; margin-bottom: 10px;" />
          <el-skeleton-item variant="p" style="height: 20px; margin-bottom: 10px;" />
          <el-skeleton-item variant="p" style="height: 20px; margin-bottom: 10px;" />
        </template>
      </el-skeleton>
    </div>
  </el-drawer>
</template>

<script setup lang="ts">
import { ref, watch } from '@vue/runtime-core'
import { ElMessage } from 'element-plus'
import { getSalesOrderDetail, updateSalesOrder } from '@/api/sales'
import type { Order } from '../types'

// 定义组件属性
interface Props {
  modelValue: boolean
  orderId?: string
}

const props = defineProps<Props>()

// 定义组件事件
const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
  (e: 'success'): void
}>()

// 响应式数据
const visible = ref(false)
const order = ref<Order | null>(null)
const orderFormRef = ref()
const orderForm = ref({
  platformOrderId: '',
  platformSource: 'zcy',
  customerName: '',
  contactPerson: '',
  amount: 0,
  orderDate: '',
  orderStatus: 'pending',
  invoiceStatus: 'uninvoiced',
  responsibleSalesman: '',
  hasGift: false
})

// 表单验证规则
const rules = {
  platformOrderId: [{ required: true, message: '请输入订单编号', trigger: 'blur' }],
  platformSource: [{ required: true, message: '请选择平台来源', trigger: 'change' }],
  customerName: [{ required: true, message: '请输入客户名称', trigger: 'blur' }],
  amount: [{ required: true, message: '请输入订单金额', trigger: 'blur' }],
  orderDate: [{ required: true, message: '请选择订单日期', trigger: 'change' }],
  orderStatus: [{ required: true, message: '请选择订单状态', trigger: 'change' }],
  invoiceStatus: [{ required: true, message: '请选择发票状态', trigger: 'change' }]
}

// 监听modelValue变化
watch(() => props.modelValue, (newVal: boolean) => {
  console.log('OrderEditDrawer modelValue changed to:', newVal);
  visible.value = newVal
  if (newVal && props.orderId) {
    loadOrderDetail(props.orderId)
  }
})

// 监听visible变化
watch(visible, (newVal: boolean) => {
  console.log('OrderEditDrawer visible changed to:', newVal);
  emit('update:modelValue', newVal)
  if (!newVal) {
    order.value = null
  }
})

// 获取订单详情
const loadOrderDetail = async (orderId: string) => {
  try {
    const response = await getSalesOrderDetail(Number(orderId))
    order.value = response.data
    
    // 填充表单数据
    if (order.value) {
      orderForm.value = {
        platformOrderId: order.value.platformOrderId,
        platformSource: order.value.platformSource || 'zcy',
        customerName: order.value.customerName,
        contactPerson: order.value.contactPerson,
        amount: order.value.amount,
        orderDate: order.value.orderDate,
        orderStatus: order.value.orderStatus,
        invoiceStatus: order.value.invoiceStatus,
        responsibleSalesman: order.value.responsibleSalesman,
        hasGift: order.value.hasGift || false
      }
    }
  } catch (error) {
    ElMessage.error('获取订单详情失败')
    visible.value = false
  }
}

// 关闭抽屉
const handleClose = () => {
  visible.value = false
}

// 保存订单
const saveOrder = async () => {
  try {
    await orderFormRef.value.validate()
    
    if (props.orderId) {
      await updateSalesOrder(Number(props.orderId), orderForm.value)
      ElMessage.success('订单保存成功')
      emit('success')
      visible.value = false
    }
  } catch (error) {
    ElMessage.error('保存订单失败')
  }
}
</script>

<style scoped lang="scss">
.order-edit-content {
  padding: 20px;
  
  .form-actions {
    display: flex;
    justify-content: flex-end;
  }
}

.loading-container {
  padding: 20px;
}
</style>